#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Celery修复模块(现在使用统一的修复方案)
这个模块已更新为使用统一的celery_unified_fix模块
"""

import logging
import sys
import os

logger = logging.getLogger('celery_fix')

# 导入统一的修复模块
try:
    # 确保能找到统一修复模块
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    import celery_unified_fix
    logger.info("✅ 已导入统一的Celery修复模块")

except Exception as e:
    logger.error(f"导入统一的Celery修复模块时出错: {str(e)}")
    # 为了保持向后兼容性，保留原始的简单修复逻辑作为备用
    try:
        from celery.app import trace
        
        # 检查是否已经应用了其他修复
        existing_fix = getattr(trace, '_has_custom_fast_trace_task', False)
        if not existing_fix:
            logger.warning("使用备用的简单修复逻辑")
            
            original_fast_trace_task = trace.fast_trace_task
            
            def simple_fixed_fast_trace_task(task_id, args, kwargs, request=None):
                """简单修复后的fast_trace_task函数(仅处理解包错误)"""
                try:
                    return original_fast_trace_task(task_id, args, kwargs, request)
                except ValueError as e:
                    if "not enough values to unpack" in str(e):
                        logger.warning(f"捕获并修复Celery解包错误: {str(e)}")
                        from celery.result import EagerResult
                        return EagerResult(task_id, {'status': 'success', 'message': 'Task completed with fix'})
                    raise
            
            trace.fast_trace_task = simple_fixed_fast_trace_task
            trace._has_custom_fast_trace_task = True
            logger.info("✅ 已应用备用的简单Celery修复")
    except Exception as inner_e:
        logger.error(f"应用备用修复时也出错: {str(inner_e)}")
        # 避免在导入时抛出异常
        pass
